package net.oschina.task;

import net.oschina.db.SQL;
import net.oschina.parse.Parser;
import net.oschina.sendmail.Mail;

import java.io.*;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * Created by rex on 2015/3/9.
 */
public class Task {
    private static long period = 0;
    private static int page = 1;
    private static String host;
//    private static int port;
    private static String user;
    private static String password;
    private static String subject;

    public static void list(String location, String attach){
        SQL sql = null;
        try {
            sql = new SQL();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        System.out.println("[fetching...]");
        int userNum = 0;

        Parser p = new Parser(sql);
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            try{
                userNum = p.ParseList((i + 1), location, "");
            }catch (Exception e){
                System.out.println("[W] parse list failed.");
            }

        }

        // self define attach
        if (attach.length()>0){
            for (int i = 0; i < 10; i++) {
                System.out.println("[page] "+ (i + 1));
                p.ParseList((i + 1), location, attach);
            }
            System.out.println("[finised fetch]");
            return;
        }

        if (userNum<=1000){
            System.out.println("[finised fetch]");
            return;
        }

        // the next will fetch extra user via condition
//        String attach = "";

        ////////////////////////////////////////////////////
        attach = "&sort=followers&order=asc";
        // &sort=followers&order=asc
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            p.ParseList((i + 1), location, attach);
        }

        attach = "&sort=followers&order=desc";
        // &sort=followers&order=desc
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            p.ParseList((i + 1), location, attach);
        }

        ////////////////////////////////////////////////////
        attach = "&sort=joined&order=desc";
        // &sort=joined&order=asc
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            p.ParseList((i + 1), location, attach);
        }

        attach = "&sort=joined&order=desc";
        // &sort=joined&order=desc
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            p.ParseList((i + 1), location, attach);
        }

        ////////////////////////////////////////////////////
        attach = "&sort=repositories&order=desc";
        // &sort=repositories&order=asc
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            p.ParseList((i + 1), location, attach);
        }

        attach = "&sort=repositories&order=desc";
        // &sort=repositories&order=desc
        for (int i = 0; i < 10; i++) {
            System.out.println("[page] "+ (i + 1));
            p.ParseList((i + 1), location, attach);
        }

        System.out.println("[finised fetch]");
    }

    public static void getEmail(){
        System.out.println("update email");
        // TODO: get all emails
        SQL sql = null;
        try {
             sql = new SQL();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        List<Map<String, Object>> list =  sql.GetUserList();

        for (int i = 0; i < list.size(); i++) {
            String username = list.get(i).get("username").toString();
            Parser p = new Parser(sql);
            p.ParseUserEmailFromPage(username);
        }
    }

    public static void getEmailPatch(){
        System.out.println("patch update email");
        // TODO: get all emails
        SQL sql = null;
        try {
            sql = new SQL();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        List<Map<String, Object>> list =  sql.GetUserListPatch();

        for (int i = 0; i < list.size(); i++) {
            String username = list.get(i).get("username").toString();
            Parser p = new Parser(sql);
            p.ParseUserEmailFromPage(username);
        }
    }

    public static int getNum(String location){
        SQL sql = null;
        try {
            sql = new SQL();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        Parser p = new Parser(sql);
        return p.ParseUserNumber(location);
    }

    private static String readFileAsString(String filePath) throws IOException {
        StringBuffer fileData = new StringBuffer();
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    public static void sendMail(String configPath){
        // Read configuration
        Properties prop = new Properties();
        InputStream in = null;

        File f = new File(configPath);
        try {
            in = new FileInputStream(f);
        } catch (FileNotFoundException e) {
            System.out.println("[E] open mail config file failed");
            return;
        }

        try {
            prop.load(in);
            host = prop.getProperty("host").trim();
            user = prop.getProperty("user").trim();
            password = prop.getProperty("password").trim();
        } catch (IOException e) {
            System.out.println("[E] Read Email configuration failed");
        }

        // get template
        String mailTplPath = System. getProperty ("user.dir")+System.getProperty("file.separator")+"mail.tpl";
        String mailContent = "";
        String subjectPath = System. getProperty ("user.dir")+System.getProperty("file.separator")+"subject";
        try {
            mailContent = readFileAsString(mailTplPath);
            subject = readFileAsString(subjectPath);
        } catch (IOException e) {
            System.out.print("[E] 邮件主题文件或邮件模版读取失败");
            return;
        }

        // get mail list
        SQL sql = null;
        try {
            sql = new SQL();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        List<Map<String, Object>> list =  sql.GetUserEmailList();
        for (int i = 0; i < list.size(); i++) {
            String username = list.get(i).get("username").toString();
            String email = list.get(i).get("email").toString();
            // send mail
            boolean result = Mail.send(host, user, email, subject, mailContent, user, password);
            if (result){
                // send mail success
                sql.UpdateEmailHasSend(username);
            }
        }
    }
}
